package com.ibm.fs.flow;

import java.beans.IntrospectionException;
import java.io.*;




import org.apache.commons.betwixt.io.BeanReader;
import org.apache.commons.betwixt.io.BeanWriter;
import org.xml.sax.SAXException;

import com.ibm.demoBankJSF.config.Constants;

public class ParserXML {

	public FlowBean readXML(){
		FlowBean flow = null;
		
		// First construct the xml which will be read in
		// For this example, read in from a hard coded string
		FileOutputStream fout = null;
		try {
			fout = new FileOutputStream (Constants.xmlNavegationPath);
		} catch (FileNotFoundException e1) {
			e1.printStackTrace();
		}
		if (fout != null){
			StringReader xmlReader = new StringReader(fout.toString());
			// Now convert this to a bean using betwixt
			// Create BeanReader
			BeanReader beanReader  = new BeanReader();

			// Configure the reader
			// If you're round-tripping, make sure that the configurations are compatible!
			beanReader.getXMLIntrospector().getConfiguration().setAttributesForPrimitives(false);
			beanReader.getBindingConfiguration().setMapIDs(false);

			// Register beans so that betwixt knows what the xml is to be converted to
			// Since the element mapped to a PersonBean isn't called the same 
			// as Betwixt would have guessed, need to register the path as well

			flow = new FlowBean();
			try {
				beanReader.registerBeanClass("flow", FlowBean.class);
				flow = (FlowBean) beanReader.parse(xmlReader);
			} 
			catch (IntrospectionException e) {
				e.printStackTrace();
			} 
			catch (IOException e) {
				e.printStackTrace();
			} 
			catch (SAXException e) {
				e.printStackTrace();
			}
		}
		return flow;
	}

	public void writeXML (FlowBean flow){
		// Start by preparing the writer
		// We'll write to a string 
		StringWriter outputWriter = new StringWriter(); 

		// Betwixt just writes out the bean as a fragment
		// So if we want well-formed xml, we need to add the prolog
		outputWriter.write("<?xml version='1.0' ?>\n");

		// Create a BeanWriter which writes to our prepared stream
		BeanWriter beanWriter = new BeanWriter(outputWriter);

		// Configure betwixt
		// For more details see java docs or later in the main documentation
		beanWriter.getXMLIntrospector().getConfiguration().setAttributesForPrimitives(false);
		beanWriter.getBindingConfiguration().setMapIDs(false);
		beanWriter.enablePrettyPrint();

		// If the base element is not passed in, Betwixt will guess 
		try {
			beanWriter.write("flow", flow);
			System.out.println(outputWriter.toString());
			outputWriter.close();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (SAXException e) {
			e.printStackTrace();
		} catch (IntrospectionException e) {
			e.printStackTrace();
		}        
	}
}
